package com.codeoss.framework.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.codeoss.framework.context.YunContext;
import com.codeoss.framework.converter.IConverter;
import com.codeoss.framework.converter.IConverterStore;
import com.codeoss.framework.data.metadata.Column;
import com.codeoss.framework.data.metadata.Table;
import com.codeoss.framework.data.store.ITableStore;
import com.codeoss.framework.rest.RestResponse;

@Component
public class RestUtil {
	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private ITableStore tableStore;
	@Autowired
	private IConverterStore converterStore;
	public List<Map<String,Object>> select(String url,String tableName){
		HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> request = new HttpEntity<>(null, headers);
        
        if(url.indexOf("?")==-1) {
        	url+="?";
        }else {
        	url+="&";
        }
        url+="token="+YunContext.getCurrentContext().getToken();
		ResponseEntity<RestResponse> responseEntity=null;
		try {
			responseEntity = restTemplate.postForEntity(url,request,RestResponse.class);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
		RestResponse restResponse=responseEntity.getBody();
		
		Table table=tableStore.get(tableName);
		List<Column> columnList=table.getAllColumnList();
		List<Map<String,String>> data=restResponse.getData();
		
		List<Map<String,Object>> newData=new ArrayList<Map<String,Object>>();
		
		for(int i=0;i<data.size();i++) {
			Map<String,String> map=data.get(i);
			Map<String,Object> newMap=new HashMap<String,Object>();
			newData.add(newMap);
			for(int j=0;j<columnList.size();j++) {
				Column column=columnList.get(j);
				Iterator<Map.Entry<String, String>>it= map.entrySet().iterator();
				while(it.hasNext()) {
					Map.Entry<String, String> entry=it.next();
					if(entry.getKey().equalsIgnoreCase(column.getProperty())){
						String sValue=entry.getValue();
						if(!StringUtils.isEmpty(sValue)) {
							IConverter converter=converterStore.getConverter(column.getDataType());
							Object value=converter.convertStringToObject(sValue);
							newMap.put(column.getColumnName(), value);
						}else {
							newMap.put(column.getColumnName(), null);
						}
						break;
					}
				}
			}
		}
		return newData;
	}
}
